#!/usr/bin/python
#coding=utf8

import os, sys, time, platform, subprocess, requests, urllib.request
from pyqrcode import QRCode

"""
生成10位时间戳
:return: 时间戳
"""
def generate_timestamp_10bit():
    return int(time.time())


"""
生成13位时间戳
:return: 时间戳
"""
def generate_timestamp_13bit():
    return int(time.time() * 1000)


"""
生成headers
:param referer: 引用地址
:param host: 访问地址
:return: headers
"""
def generate_headers(referer, host):
    return {
        'Referer': referer,
        'Host': host.strip('https://').strip('http://'),
        'content-type': 'application/json',
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, sdch, br',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
    }


"""
测试网络连接
:param url: 连接的url
:param retryTime: 重试次数
:return: 是否正常
"""
def test_connect(url, retryCount=5):
    for i in range(retryCount):
        try:
            r = requests.get(url)
            return True
        except:
            if i == retryCount - 1:
                return False


"""
在终端中显示二维码图案
:param text: 二维码的内容
:return: 转换后的二维码图案
"""
def print_terminal_qrcode(text:str):
    sys.stdout.write(' ' * 50 + '\r')
    sys.stdout.flush()
    qr = QRCode(text).text(1).replace('0', u'\u2588').replace('1', '  ') # '█'
    sys.stdout.write(qr)
    sys.stdout.flush()
    return qr


"""
保存网络文件
:param url: 文件的url地址
:param filePath: 将要保存文件的路径
"""
def save_http_file(url, filePath):
    urllib.request.urlretrieve(url, filePath)


"""
调用图片浏览器浏览图片
:param filePath: 图片的地址
"""
def show_image(filePath):
    OSName = platform.system()
    if 'Darwin' == OSName:
        subprocess.call(['open', filePath])
    elif 'Linux' == OSName:
        subprocess.call(['xdg-open', filePath])
    else:
        os.startfile(filePath)
